﻿Partial Public Class SampleExplorer

    Public CurrentNewRow As DataRow
    Public Routing_LookupView As GridView = Nothing
    Public WithEvents Routing_LookupEdit As GridLookUpEdit
    Public aSocietyRow As DataRow

    'Public Sub Init_TreeActionOptionList(sender As Object, e As EventArgs)
    '    Me.TreeActionOptionList.Add(New ActionOption("Sample", "ACT_00073", "Create New Quality Sheet", AddressOf TreeListMenu_NewSampleHeader, True, True, 0))
    '    'OutstandingIssue: a enlever quand le DefaultOptionList marchera ok - aleblanc
    '    Me.TreeActionOptionList.Add(New ActionOption("Sample1", "ACT_00073", "Create New Quality Sheet", AddressOf TreeListMenu_NewSampleHeader, True, True, 1))
    'End Sub

    Public Sub TreeActionOptionListLoad()
        Me.MetaControlTreeListActionOptionList.Add(New ActionOption("Sample", "ACT_00073", "Create New Quality Sheet", AddressOf TreeListMenu_NewSampleHeader, True, True, 0))
        'OutstandingIssue: a enlever quand le DefaultOptionList marchera ok - aleblanc
        Me.MetaControlTreeListActionOptionList.Add(New ActionOption("Sample1", "ACT_00073", "Create New Quality Sheet", AddressOf TreeListMenu_NewSampleHeader, True, True, 1))
    End Sub

    Public Overridable Sub TreeListMenu_NewSampleHeader(ByVal sender As Object, ByVal e As EventArgs)
        Me.Cursor = Cursors.WaitCursor

        ShowBySampleHeader(Guid.Empty)
        '
        'On trouve la form pour effacer les controle dedans et ensuite remettre le bon.
        'Comme ca on change le Detail selon la ligne dans L'explorer
        For Each aFrm As XtraForm In Me.ParentForm.MdiChildren
            If aFrm.Name = PanelName Then
                aFrm.Controls.Clear()
                aFrm.Controls.Add(aGridControl)
                aFrm.Text = "New Quality Sheet"
                aFrm.Show()
                aFrm.Focus()
            End If
            aFrm.Refresh()
        Next
        Me.Cursor = Cursors.Default
    End Sub

    Public Overridable Sub SampleHeader_InitNewMasterRow(ByVal sender As Object, ByVal e As InitNewRowEventArgs)
        Dim view As GridView = CType(sender, GridView)
        Dim row As DataRow = view.GetFocusedDataRow()
        row("QAQCInspLotID") = Guid.NewGuid
        row("Dt_Utilisation") = Date.Now 'AnalysisDate
        row("SampleDT") = Date.Now 'Lot Sample Date

    End Sub

    Public Overridable Sub SampleHeader_ValidateMasterRow(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs)
        Dim row As DataRow = CType(e.Row, DataRowView).Row
        Using plSample As SystemBoxSDK.PL.MESSDK.SampleHeader_PL = New SystemBoxSDK.PL.MESSDK.SampleHeader_PL()
            plSample.ValidateRow(row)
        End Using
    End Sub

    ''' <summary>
    ''' When a column containing a lookupEdit is clicked, we use this Event to be able to filter the content.
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Public Overridable Sub SampleHeader_ShownMasterEditor(sender As Object, e As System.EventArgs)
        Dim aView As GridView = CType(sender, GridView)
        CurrentNewRow = aView.GetFocusedDataRow()
        Dim edit As GridLookUpEdit


        If TypeOf aView.ActiveEditor Is GridLookUpEdit Then
            edit = CType(aView.ActiveEditor, GridLookUpEdit)
            edit.Properties.View.ActiveFilterEnabled = False

            'If aView.FocusedColumn.FieldName = "LotRoutingID_FK" AndAlso CurrentNewRow IsNot Nothing And Not aView.FocusedRowHandle.Equals(GridControl.AutoFilterRowHandle) Then
            If aView.FocusedColumn.FieldName = "LotRoutingID_FK" And Not aView.FocusedRowHandle.Equals(GridControl.AutoFilterRowHandle) Then
                'Scoping_LOV_LotRouting(edit)

            ElseIf aView.FocusedColumn.FieldName = "PrdID_FK" And Not aView.FocusedRowHandle.Equals(GridControl.AutoFilterRowHandle) Then
                Scoping_LOV_Product(edit)

            ElseIf aView.FocusedColumn.FieldName = "RoutingId_FK" And Not aView.FocusedRowHandle.Equals(GridControl.AutoFilterRowHandle) Then
                Scoping_LOV_Routing(edit)

                If TypeOf aView.ActiveEditor Is GridLookUpEdit Then
                    Routing_LookupEdit = CType(aView.ActiveEditor, GridLookUpEdit)
                End If
            End If
        End If
    End Sub

    Public Overridable Sub Routing_LookupEdit_CloseUp(sender As Object, e As DevExpress.XtraEditors.Controls.CloseUpEventArgs) Handles Routing_LookupEdit.CloseUp
        Dim alookup As GridLookUpEdit = DirectCast(sender, GridLookUpEdit)

        If alookup.Properties.ValueMember = "RoutingId" Then
            Routing_LookupView = alookup.Properties.View
        End If
    End Sub

    ''' <summary>
    ''' This Sub will scope the LotRouting LOV, depending on the selected Lot
    ''' </summary>
    ''' <param name="edit"></param>
    ''' <remarks></remarks>
    Public Overridable Sub Scoping_LOV_LotRouting(ByVal edit As GridLookUpEdit)
        Dim LotId As Guid

        If CurrentNewRow Is Nothing OrElse IsDBNull(CurrentNewRow("LotId_FK")) Then
            LotId = Guid.Empty
        Else
            LotId = If(IsDBNull(CurrentNewRow), Guid.Empty, CType(CurrentNewRow("LotId_FK"), Guid))
        End If

        edit.Properties.View.ActiveFilterString = String.Format(" AND LotID_FK = '{0}' ", LotId)
        edit.Properties.View.OptionsView.ShowFilterPanelMode = Views.Base.ShowFilterPanelMode.Never

    End Sub

    ''' <summary>
    ''' This Sub will scope the Product LOV, depending on the selected Site
    ''' </summary>
    ''' <param name="edit"></param>
    ''' <remarks></remarks>
    Public Overridable Sub Scoping_LOV_Product(ByVal edit As GridLookUpEdit)
        Dim SiteId As Guid

        If CurrentNewRow Is Nothing OrElse IsDBNull(CurrentNewRow("WhouseID_FK")) Then
            SiteId = Guid.Empty
        Else
            SiteId = If(IsDBNull(CurrentNewRow("WhouseID_FK")), Guid.Empty, CType(CurrentNewRow("WhouseID_FK"), Guid))
        End If

        edit.Properties.View.ActiveFilterString = String.Format("Inactive = False and SiteId_FK = '{0}'", SiteId)
        edit.Properties.View.OptionsView.ShowFilterPanelMode = Views.Base.ShowFilterPanelMode.Never
    End Sub

    ''' <summary>
    ''' This Sub will scope the Routing LOV, depending on the selected Product
    ''' </summary>
    ''' <param name="edit"></param>
    ''' <remarks></remarks>
    Public Overridable Sub Scoping_LOV_Routing(ByVal edit As GridLookUpEdit)
        Dim PrdId As Guid
        Dim SiteId As Guid

        If CurrentNewRow Is Nothing OrElse IsDBNull(CurrentNewRow("WhouseID_FK")) Then
            PrdId = Guid.Empty
            SiteId = Guid.Empty
        Else
            PrdId = If(IsDBNull(CurrentNewRow("PrdID_FK")), Guid.Empty, CType(CurrentNewRow("PrdID_FK"), Guid))
            SiteId = If(IsDBNull(CurrentNewRow("WhouseID_FK")), Guid.Empty, CType(CurrentNewRow("WhouseID_FK"), Guid))
        End If

        edit.Properties.View.ActiveFilterString = String.Format("IsActivated = True AND SiteId_FK = '{0}' AND PrdID_FK = '{1}'", SiteId, PrdId)
        edit.Properties.View.OptionsView.ShowFilterPanelMode = Views.Base.ShowFilterPanelMode.Never
    End Sub


    Public Overridable Sub SampleHeader_MasterCellValueChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs)
        Dim aView As GridView = DirectCast(sender, GridView)
        Dim aRow As System.Data.DataRow = aView.GetDataRow(e.RowHandle)

        'OUTSTANDINGISSUE: Il faudrait remettre a blanc les valeurs des colonnes dans certains cas. Ex: si on change de Site il faudrait clearer les colonnes Product et Routing. clieng

        If e.Column.FieldName.Equals("PrdID_FK") AndAlso aRow IsNot Nothing Then

            'By default we take Prd Qte - aleblanc
            If Not IsDBNull(aRow("PrdID_FK")) Then
                Dim aProductRow As System.Data.DataRow = SystemBoxSDK.PL.CoreSDK.Product_PL.GetProductByID(CType(aRow("PrdID_FK"), Guid))
                If aProductRow IsNot Nothing Then
                    aRow("RequestedQty") = aProductRow("ProductionQty")
                End If
            End If
        ElseIf e.Column.FieldName.Equals("LotId_FK") AndAlso aRow IsNot Nothing Then
            If Not IsDBNull(aRow("LotId_FK")) Then
                Dim aLotRow As System.Data.DataRow = SystemBoxSDK.PL.MESSDK.Lot_PL.GetLotByID(CType(aRow("LotId_FK"), Guid))
                If aLotRow IsNot Nothing Then

                    aRow("LotTypeID_FK") = aLotRow("LotTypeID_FK")
                    aRow("LotDescr_Prm") = aLotRow("LotDescr_Prm")
                    aRow("WhouseID_FK") = aLotRow("WhouseID_FK")
                    aRow("PrdID_FK") = aLotRow("PrdID_FK")
                    aRow("RequestedQty") = aLotRow("RequestedQty")
                    aRow("RoutingId_FK") = Guid.Empty

                End If
            End If
        ElseIf e.Column.FieldName.Equals("QAStatID_FK") AndAlso aRow IsNot Nothing Then
            'Equivalent de l'ancient trigger : UpdateStatus sur la table QAQCInspLot. clieng 2012-11-15
            If Not IsDBNull(aRow("QAStatID_FK")) AndAlso Not String.IsNullOrEmpty(aRow("QAStatID_FK")) Then
                If aRow("QAStatID_FK") = IdRepository.APP_SAMPLESTATUS_OPEN Then
                    aRow("QAStat") = "O"
                    aRow("StatusId_FK") = IdRepository.APP_SAMPLESTATUS_OPEN

                ElseIf aRow("QAStatID_FK") = IdRepository.APP_SAMPLESTATUS_CLOSED Then
                    aRow("QAStat") = "C"
                    aRow("QAStatID_FK") = IdRepository.APP_SAMPLESTATUS_CLOSED
                End If
            End If
        End If
    End Sub

    Public Overridable Sub SampleHeader_ContextMenuBeforePopup(sender As Object, e As EventArgs)
        Dim aMenu As DevExpress.XtraGrid.Menu.GridViewMenu = CType(sender, GridViewMenu)
        Dim row As DataRow = aMenu.View.GetFocusedDataRow()

        If row IsNot Nothing Then
            Dim i As Integer = 0
            'For Each item In aMenu.Items
            While i < aMenu.Items.Count
                If aMenu.Items(i).Caption = "Delete" Then
                    aMenu.Items(i).Enabled = False
                End If

                'If (aMenu.Items(i).Caption.Contains("Revise") OrElse aMenu.Items(i).Caption.Contains("Limit")) Then

                '    If IMExplorer.IMActivated OrElse Not IMExplorer.BOMEnabled OrElse Not CBool(row("IsCopy")) Then
                '        aMenu.Items(i).Enabled = False
                '    End If
                'End If
                i += 1
            End While
        End If
    End Sub

    Public Overridable Sub SampleHeader_Remove(ByVal sender As System.Object, ByVal e As EventArgs)
        'Dim view As GridView = CType(DetailGridControl.GridControl1.FocusedView, GridView)
        Dim aRow As DataRow = CType(CType(sender, DXMenuItem).Tag, DataRow)

        If aRow IsNot Nothing Then
            Try
                Dim sqlcmd As System.Data.SqlClient.SqlCommand = Nothing

                Try
                    sqlcmd = MetaQuery.GetSPCmdByMetaName("SampleHeader_Delete")
                    'Match les parametres de la SP avec les colonne de la grilles
                    For Each pr As System.Data.SqlClient.SqlParameter In sqlcmd.Parameters
                        If aRow.Table.Columns.Contains(pr.SourceColumn) Then
                            sqlcmd.Parameters(pr.ParameterName).Value = aRow(pr.SourceColumn)
                        End If
                    Next
                    sqlcmd.ExecuteNonQuery()
                    MessageWindow.ShowMessage("Remove done. Please refresh screen.")
                Catch sqlex As System.Data.SqlClient.SqlException
                    Throw sqlex
                Finally
                    If sqlcmd IsNot Nothing Then
                        sqlcmd.Dispose()
                    End If
                End Try


                'Refresh Screen
                'DetailGridControl.ReloadGrid()
            Catch sqlex As System.Data.SqlClient.SqlException
                If sqlex.Number = 50000 Then
                    MessageWindow.ShowMessage("Cannot delete Sample. Changes was made.")
                Else
                    MessageWindow.ShowMessage(sqlex)
                End If
            End Try
        End If
    End Sub

    Public Overridable Sub SampleHeader_Delete(ByVal row As DataRow, ByVal e As CancelEventArgs)
        If row.Table.TableName.Equals("SampleHeader") Then
            e.Cancel = True
        ElseIf row.Table.TableName.Equals("SampleDetail") Then
            If CDate(row("Crtd_DT").ToString).ToString("yyyy/MM/dd hh:mm") <> CDate(row("LUpd_DT").ToString).ToString("yyyy/MM/dd hh:mm") Then
                e.Cancel = True
                MessageWindow.ShowMessage("Cannot delete Sample. Changes was made.")
            End If
        End If
    End Sub

    Public Overridable Sub SampleHeader_MasterCustomRowCellEditForEditing(ByVal sender As Object, ByVal e As CustomRowCellEditEventArgs)
        Dim aDetailview As GridView = DirectCast(sender, GridView)
        Dim aRow As DataRow = aDetailview.GetFocusedDataRow()

        'Dim aDetailview As GridView = DirectCast(sender, GridView)
        'Dim aRow As DataRow = aDetailview.GetRow(e.RowHandle)

        If e.Column.FieldName = "LotRoutingID_FK" Then
            'On filtre pas si c'est la ligre de recherche
            If Not aDetailview.FocusedRowHandle.Equals(GridControl.AutoFilterRowHandle) Then
                Dim aEdit As RepositoryItemGridLookUpEdit
                Dim LotId As Guid
                Dim sqlWhere As String

                If aRow IsNot Nothing AndAlso Not IsDBNull(aRow("LotId_FK")) Then
                    LotId = If(IsDBNull(aRow), Guid.Empty, CType(aRow("LotId_FK"), Guid))
                Else
                    LotId = Guid.Empty
                End If

                sqlWhere = String.Format("SpecGroupID_FK = '{0}' and LotID_FK = '{1}'", IdRepository.APP_SPECIFGROUP_QLTY, LotId)
                aEdit = LOVBuilder("LOV_SampleHeader_LotRouting", sqlWhere, Nothing, Nothing)
                aEdit.Name = "LOV_SampleHeader_LotRouting"
                aDetailview.GridControl.RepositoryItems.Add(aEdit)
                e.RepositoryItem = aEdit
            End If
        End If

    End Sub


    ''
    ''
    '' OutStandingIssues: A faire en Helper - aleblanc 2011-10-26
    ''
    ''
    Public formatType As DevExpress.Utils.FormatType
    ''' <summary>
    ''' use to Build a LOV for our GRID
    ''' </summary>
    ''' <param name="queryName"></param>
    ''' <param name="sqlWhere"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function LOVBuilder(ByVal queryName As String, ByVal sqlWhere As String, ByVal sqlFrom As String, ByVal filter As String) As RepositoryItemGridLookUpEdit
        Dim aEdit As RepositoryItemGridLookUpEdit
        Dim colVisible As Boolean
        Dim hideCol As Boolean
        Dim colname As String
        Dim Column As DevExpress.XtraGrid.Columns.GridColumn
        Dim view As Views.Base.ColumnView

        Using mq As MetaQuery = MetaQuery.GetMetaQueryByName(queryName)
            If Not String.IsNullOrWhiteSpace(sqlWhere) Then
                mq.SQLWhere = sqlWhere
            End If
            '

            'ICI Le DataField filter appliquer quand on a la securité
            If Not String.IsNullOrWhiteSpace(sqlFrom) Then
                mq.SQLFrom = String.Concat(mq.SQLFrom, sqlFrom)
            End If

            If Not String.IsNullOrWhiteSpace(filter) Then
                mq.SQLWhere = String.Concat(mq.SQLWhere, filter)
            End If
            '
            mq.FillResultQuery()
            aEdit = New RepositoryItemGridLookUpEdit() With {.DataSource = mq.ResultQuery, .DisplayMember = mq.ResultQuery.Columns(CommonExt.Base.AppManager.ApplicationOption.DescriptionColumnIndex).ToString, .ValueMember = mq.GUIDField, .PopupFormSize = New Size(800, 300), .NullText = "(none)"}
            aEdit.View.HorzScrollVisibility = Views.Base.ScrollVisibility.Always
            aEdit.View.OptionsView.ColumnAutoWidth = False
            aEdit.View.OptionsView.ShowAutoFilterRow = True
            aEdit.View.OptionsBehavior.ReadOnly = True
            view = aEdit.View
            view.Columns.Clear()
            For Each row As DataRow In mq.MetaColumns.Rows
                colname = row("ColumnName").ToString
                hideCol = False
                If AppManager.ApplicationOption.DescriptionColumnIndex = 2 Then
                    If colname.EndsWith("_ALT") Then
                        hideCol = True
                    End If
                Else
                    If colname.EndsWith("_PRM") Then
                        hideCol = True
                    End If
                End If
                If hideCol = False Then
                    colVisible = CBool(IIf(CInt(row("pVisible")) = 0, False, True))
                    Column = view.Columns.AddField(colname)
                    Column.VisibleIndex = CInt(row("pOrder"))
                    Column.Caption = row("pCaption").ToString
                    Column.Visible = colVisible
                    Column.Width = CInt(row("pWidth"))
                    Column.ToolTip = row("pToolTip").ToString

                    formatType = GetFormatType(row)
                    '
                    Column.DisplayFormat.FormatType = formatType
                    Column.DisplayFormat.FormatString = row("pNumberFormat").ToString
                End If
            Next
            aEdit.DataSource = mq.ResultQuery
            Return aEdit
        End Using
    End Function

    Public Function GetFormatType(ByVal arow As DataRow) As DevExpress.Utils.FormatType
        If (Not String.IsNullOrEmpty(arow("pNumberFormatID_FK").ToString)) Then
            Select Case CType(arow("pNumberFormatID_FK"), Guid)

                Case CommonExt.Base.IdRepository.META_NUMBERFORMAT_CURRENCY, CommonExt.Base.IdRepository.META_NUMBERFORMAT_GENERALNUMBER, CommonExt.Base.IdRepository.META_NUMBERFORMAT_PERCENT, CommonExt.Base.IdRepository.META_NUMBERFORMAT_STANDARD, CommonExt.Base.IdRepository.META_NUMBERFORMAT_SCIENTIFIC
                    Return DevExpress.Utils.FormatType.Numeric

                Case CommonExt.Base.IdRepository.META_NUMBERFORMAT_GENERALDATE, CommonExt.Base.IdRepository.META_NUMBERFORMAT_LONGDATE, CommonExt.Base.IdRepository.META_NUMBERFORMAT_LONGTIME, CommonExt.Base.IdRepository.META_NUMBERFORMAT_MEDIUMDATE, CommonExt.Base.IdRepository.META_NUMBERFORMAT_MEDIUMTIME, CommonExt.Base.IdRepository.META_NUMBERFORMAT_SHORTDATE, CommonExt.Base.IdRepository.META_NUMBERFORMAT_SHORTTIME
                    Return DevExpress.Utils.FormatType.DateTime

                Case CommonExt.Base.IdRepository.META_NUMBERFORMAT_FORMATEXPR
                    Return DevExpress.Utils.FormatType.Custom

                Case Else
                    Return DevExpress.Utils.FormatType.None
            End Select
        Else
            Return DevExpress.Utils.FormatType.None
        End If
    End Function
    ''
    ''
    '' OutStandingIssues: FIN A faire en Helper - aleblanc 2011-10-26
    ''
    ''
End Class
